/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.xml.xpath.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author BEHIEN
 */
public class SelectQuery {
    /*public static void main(String[] args) {
            //parse("select id, tablename from mytable , table");//put here your query string
          parse("select id, tablename from mytable where mytable = 'banhoc'");
      }*/
    public static void parse(String theString) throws XPathExpressionException{
            StringTokenizer st=new StringTokenizer(theString.toLowerCase()," ,");
            int state=0;//0=select;1=from;2=where
            ArrayList<String> select=new ArrayList<String>();
            ArrayList<String> from=new ArrayList<String>();
            ArrayList<String> where=new ArrayList<String>();
            while (st.hasMoreTokens()){
                  String theToken=st.nextToken();
                  System.out.println("Token:"+theToken);
                  //here you can check if you are in select zone, from zone, or where zone or...
                  //and you can decide what you want to do
                  if (theToken.equals("select"))state=0;
                  else if (theToken.equals("from"))state=1;
                  else if (theToken.equals("where"))state=2;
                  else {
                        if (state==0)select.add(theToken);
                        if (state==1)from.add(theToken);
                        if (state==2)where.add(theToken);
                  }
            }
            String [] selectitem = select.toArray(new String[0]);
            String [] fromitem = from.toArray(new String[0]);
            String [] whereitem = where.toArray(new String[0]);
            
            CreateSelectXML(selectitem, fromitem, whereitem);
                    
            //here the vectors select, from and where have what you are looking for
            System.out.println("NR of TOKEN IN SELECT:"+ select.toString());
            System.out.println("NR of TOKEN IN FROM:"+from.toString());
            System.out.println("NR of TOKEN IN WHERE:"+where.toString());
      }
        
      public static int CreateSelectXML(String[] colsset, String[] tablesset, String[] conditionsset) throws XPathExpressionException {
                MetaManipulation.init_select();
		Document doc = MetaManipulation.load_select();
		if (doc == null)
			return MetaManipulation.ErrorLoading;
                String nasel = "tagselect";
                Element rootElement = doc.getDocumentElement();

                Element selects = doc.createElement("selects");
                Attr attr = doc.createAttribute("name");
                attr.setValue(nasel);
                selects.setAttributeNode(attr);

                rootElement.appendChild(selects);

                MetaManipulation.save_select(doc);
		
		doc = MetaManipulation.load_select();
		if (doc == null)
			return MetaManipulation.ErrorLoading;
                
                try
		{
                    XPath xpath = XPathFactory.newInstance().newXPath();
                    XPathExpression expr = xpath.compile("//selects[@name='"+nasel+"']");

                    Element tbNode = (Element) expr.evaluate(doc, XPathConstants.NODE);
                    Element select = doc.createElement("select");

                    for(int i = 0; i < colsset.length; i++)
                    {       
                            Element cols = doc.createElement("column");
                            cols.setTextContent(colsset[i]);

                            select.appendChild(cols);	
                    }
                    tbNode.appendChild(select);

                    Element from = doc.createElement("from");
                    if (doc == null)
                            return MetaManipulation.ErrorLoading;


                            /*XPath xpath = XPathFactory.newInstance().newXPath();
                            XPathExpression expr = xpath.compile("//table[@name='"
                                            + tableName + "']");

                            Element tbNode = (Element) expr.evaluate(doc, XPathConstants.NODE);*/
                            for(int i = 0; i < tablesset.length; i++)
                            {

                                    Element table = doc.createElement("table");
                                    table.setTextContent(tablesset[i]);

                                    from.appendChild(table);	
                            }

                            tbNode.appendChild(from);
                    
                    if(conditionsset.length != 0)
                    {
                        Element where = doc.createElement("where");
                    if (doc == null)
                            return MetaManipulation.ErrorLoading;

                    int i_condition = 0;
                    int[] i_int = new int[10];
                    i_int[0] = 0;
                    for(int i = 0; i < conditionsset.length; i++)
                    {
                        if(conditionsset[i].compareTo("and") == 0 || conditionsset[i].compareTo("or") == 0)
                        {
                            i_condition++;
                            i_int[i_condition] = i;

                        }

                    }
                            for(int j = 0; j < i_condition + 1; j++)
                            {
                                Element condition = doc.createElement("condition");
                                
                                for(int i = i_int[j]; i <= i_int[j]+3 ; i++)
                                {
                                        if(i%4 == 0)
                                        {
                                            Element column = doc.createElement("column");
                                            column.setTextContent(conditionsset[i]);
                                            condition.appendChild(column);
                                        }
                                        if(i%4 == 1)
                                        {
                                            Element op = doc.createElement("operator");
                                            op.setTextContent(conditionsset[i]);
                                            condition.appendChild(op);
                                        }
                                        if(i%4 == 2)
                                        {
                                            Element par = doc.createElement("parameter");
                                            par.setTextContent(conditionsset[i]);
                                            condition.appendChild(par);
                                        }	
                                }
                                where.appendChild(condition);
                            }

                            tbNode.appendChild(where);
                    }
                    
		}
		catch (Exception e) {
			return MetaManipulation.ErrorUnknown;
		}
		
		if (MetaManipulation.save_select(doc) == MetaManipulation.Success) {
			return MetaManipulation.Success;
		} else {
			return MetaManipulation.ErrorUnknown;
		}
	}
}
